package com.authorize.web.controller.common;

import com.alibaba.fastjson2.JSONObject;
import com.authorize.common.exception.TClientException;
import com.authorize.common.utils.PayUtils;
import com.authorize.common.utils.RedisUtils;
import com.authorize.common.utils.Result;
import com.authorize.system.domain.AAuth;
import com.authorize.system.domain.AGood;
import com.authorize.system.domain.AOrder;
import com.authorize.system.domain.APayConfig;
import com.authorize.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;

@RestController
@RequestMapping("/open/api")
public class OpenApiController {

    @Autowired
    private IAOrderService aOrderService;

    @Autowired
    private IAPayConfigService aPayConfigService;

    @Autowired
    private IAGoodService aGoodService;

    @Autowired
    private IAAuthService aAuthService;

    /**
     * 域名授权检测接口
     * @param req
     */
    @RequestMapping("/auth")
    public Result auth(@RequestBody String req) throws TClientException {
        Result result = new Result();
        try{
            JSONObject data = JSONObject.parseObject(req);
            String authNo = data.getString("authNo");
            String domainName = data.getString("domainName");
            if(authNo == null || domainName == null){
                throw new TClientException("检测未通过，请求参数错误！");
            }
            AAuth auth = aAuthService.selectAAuthByAuthNo(authNo);
            if(auth == null){
                throw new TClientException("检测未通过，授权编号错误！");
            }
            if(!auth.getAuthValue().equals(domainName)){
                throw new TClientException("检测未通过，该域名未经过授权！");
            }
            if(auth.getStatus() == 2){
                throw new TClientException("检测未通过，授权已到期！");
            }
            result.setMessage("检测通过！");
            //检测通过密钥生成
            String str = PayUtils.getMd5(auth.getAuthNo()+","+domainName);
            result.setData(str);
            return result;
        }catch (Exception e){
            throw new TClientException(e.getMessage());
        }
    }

    /**
     * 支付异步通知
     * @param req
     * @throws TClientException
     */
    @RequestMapping("/payNotify")
    public void payNotify(@RequestBody String req) throws TClientException {
        JSONObject data = JSONObject.parseObject(req);
        if(data.getInteger("status") == 2){
            //单线程处理业务
            RedisUtils.lock(data.getString("outTradeNo"),30000,data.getString("outTradeNo"));
            try{
                AOrder nAOrder = aOrderService.selectAOrderByOutTradeNo(data.getString("outTradeNo"));
                if(nAOrder != null && nAOrder.getStatus() == 1){
                    //判断是否是非法请求
                    APayConfig aPayConfig = aPayConfigService.selectAPayConfigById(nAOrder.getPayId());
                    if(!aPayConfig.getAppId().equals(data.getString("appid"))){
                        throw new TClientException("你这吊毛，不老老实实付款，还想破解！");
                    }
                    //查询订单如果成功了，则不处理，查询授权信息，如果成功了也不处理
                    AGood aGood = aGoodService.selectAGoodById(nAOrder.getGoodId());
                    if(aGood != null){
                        AAuth aAuth = new AAuth();
                        aAuth.setAuthEntryId(aGood.getEntryId());
                        aAuth.setAuthType(aGood.getAuthType());
                        if(aGood.getAuthType() == 1){
                            aAuth.setAuthValue(nAOrder.getAuthValue());
                        }
                        //到期时间计算 当前时间+月份
                        aAuth.setEndTime(subMonth(new Date(),Integer.parseInt(aGood.getEffectiveTime().toString())));
                        aAuth.setStatus(1);
                        aAuth.setCreateBy(nAOrder.getCreateBy());
                        aAuth.setAuthNo(nAOrder.getOutTradeNo().replace("AUTH",""));
                        AAuth auth = aAuthService.insertAAuthLock(aAuth);
                        //更新订单信息
                        nAOrder.setAuthId(auth.getId());
                        nAOrder.setAuthNo(auth.getAuthNo());
                        nAOrder.setTransactionTime(data.getDate("transactionTime"));
                        nAOrder.setUpdateTime(new Date());
                        nAOrder.setStatus(2);
                        aOrderService.updateAOrder(nAOrder);
                    }
                }
            }catch (Exception e){
                throw new TClientException(e.getMessage());
            }finally {
                RedisUtils.releaseLock(data.getString("outTradeNo"),data.getString("outTradeNo"));
            }

        }
    }

    /**
     * 退款异步通知
     * @param req
     */
    @RequestMapping("/refundNotify")
    public void refundNotify(@RequestBody String req) throws TClientException {
        JSONObject data = JSONObject.parseObject(req);
        if(data.getInteger("status") == 5){
            AOrder aOrder = aOrderService.selectAOrderByOutTradeNo(data.getString("outTradeNo"));
            if(aOrder != null){
                //判断是否是非法请求
                APayConfig aPayConfig = aPayConfigService.selectAPayConfigById(aOrder.getPayId());
                if(!aPayConfig.getAppId().equals(data.getString("appid"))){
                    throw new TClientException("你这吊毛，不老老实实付款，还想破解！");
                }
                aOrder.setStatus(5);
                aOrder.setRefundTime(new Date());
                aOrder.setUpdateTime(new Date());
                aOrderService.updateAOrder(aOrder);
            }
        }
    }

    /****
     * 增加月份时间
     * @param date 日期(2017-04-13)
     * @return 2017-05-13
     * @throws Exception
     */
    private Date subMonth(Date date,Integer month) throws Exception {
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(date);
        rightNow.add(Calendar.MONTH, month);
        Date dt1 = rightNow.getTime();
        return dt1;
    }

}
